import datetime
import time

import re

import os
from bs4 import BeautifulSoup
from selenium import webdriver
import selenium.webdriver.support.ui as ui
from openpyxl import Workbook

platform = '必联网'
ebnewURL = 'http://www.ebnew.com/'
userName = 'p17116'
passWord = '354315iFk'
keyWords = ['全自动生化分析仪', '全自动生化免疫流水线', 'HIV试剂']
keyWords1 = ['全自动生化分析仪', '全自动生化检测仪', '全自动生化检测系统', '全自动免疫分析仪', '全自动免疫检测仪',
            '全自动免疫检测系统', '全自动生化免疫分析仪', '全自动生化免疫检测仪', '全自动生化免疫检测系统',
            '全自动生化免疫一体机', '全自动生化免疫流水线', '生化试剂', '免疫试剂', '临床生化试剂', '临床免疫试剂',
            '检验试剂', '检测试剂', '诊断试剂', 'DNA试剂', '艾滋病试剂', 'HIV试剂']
tenderInfo = ['Data Submission Date', 'Data Type', 'First Published', 'Tender Reference Number ',
              'Tender Platform', 'Product', 'Tenderer', 'Institute Type', 'Release Date', 'Due Date', 'Agency',
              'Province', 'City', 'County', 'Original Announcement Type', 'Remark', 'Tender Website']
# --------------------------
today = datetime.date.today()
data_type = '起始记录'
first_published = '是'
# --------------------------
curr_folder = os.getcwd()
tender_folder = curr_folder + '\\tender_info\\'
if not os.path.exists(tender_folder):
    os.mkdir(tender_folder)
foreshow_file = tender_folder + 'tender_foreshow_data.xlsx'
# --------------------------
browser = webdriver.Chrome()
browser.maximize_window()
wait = ui.WebDriverWait(browser, 10)
browser.get(ebnewURL)
# --------------------------
time.sleep(2)
try:
    browser.find_element_by_xpath('//*[@id="not-login"]/a[1]').click()
    print('login success!')
except:
    print('login fail!')
time.sleep(2)
try:
    browser.find_element_by_xpath('//*[@id="loginForm"]/div[1]/input').send_keys(userName)
    print('user success!')
except:
    print('user fail!')
time.sleep(1)
try:
    browser.find_element_by_xpath('//*[@id="loginForm"]/div[2]/input').send_keys(passWord)
    print('pass success!')
except:
    print('pass fail!')
time.sleep(1)
try:
    browser.find_element_by_xpath('//*[@id="loginForm"]/div[3]/button').click()
    print('login success!')
except:
    print('login fail!')
time.sleep(2)
# --------------------------
try:
    browser.find_element_by_xpath('/html/body/div[1]/div[4]/div[2]/div[2]/form[1]/button').click()
    print('to search success!')
except:
    print('to search fail!')
time.sleep(2)
search_window = browser.current_window_handle
try:
    browser.find_element_by_link_text("招标预告").click()
    print('tender foreshow success!')
except:
    print('tender foreshow fail!')
time.sleep(2)
try:
    browser.find_element_by_link_text("近一周").click()
    print('one week success!')
except:
    print('one week fail!')
time.sleep(2)
work_book = Workbook()
for keyword in keyWords:
    sheet = work_book.create_sheet(keyword, index=0)
    sheet.append(tenderInfo)
    try:
        browser.find_element_by_xpath('//*[@id="searchBidProjForm"]/div[2]/div[3]/div/input').clear()
        browser.find_element_by_xpath('//*[@id="searchBidProjForm"]/div[2]/div[3]/div/input').send_keys(keyword)
        print('keyword success!')
    except:
        print('keyword fail!')
    time.sleep(1)
    try:
        browser.find_element_by_xpath('//*[@id="keyButten"]').click()
        print('do search success!')
    except:
        print('do search fail!')
    time.sleep(2)
    # --------------------------
    while 1:
        tender_html = browser.page_source
        tender_soup = BeautifulSoup(tender_html, "html5lib")
        # print(tender_soup.title.string)
        # print(browser.current_url)
        tender_list = tender_soup.select('div[class="abstract-box mg-t25 ebnew-border-bottom mg-r15"]')
        tender_list_size = len(tender_list)
        print(tender_list_size)  # 10
        for tender_node in tender_list:
            tender_type = ''
            tender_link = ''
            tender_title = ''
            tender_date = ''

            # -------------------------->>>1、招标预告
            tender_foreshow = tender_node.select('i[class="fl tag-foreshow mg-l15 mg-r15"]')
            if len(tender_foreshow) > 0:
                tender_type = tender_foreshow[0].get_text()
                print(tender_type)
                tender_info = tender_node.select('a[class="fl line-h26 abstract-title font-16 width-75 line-h20"]')
                tender_link = tender_info[0].get('href')
                print(tender_link)
                tender_title = tender_info[0].get_text()
                institute_type = '政府机构'
                if '医院' in tender_title or '妇幼保健院'in tender_title or \
                   '防治院' in tender_title or '防治所' in tender_title or '防治站' in tender_title:
                    institute_type = '医院'
                elif '卫生服务中心' in tender_title or '卫生服务站'in tender_title or \
                     '卫生院' in tender_title or '疗养院' in tender_title:
                    institute_type = '基层医疗单位'
                elif '门诊部' in tender_title or '诊所'in tender_title or \
                     '卫生所' in tender_title or '医务室' in tender_title or \
                     '保健所' in tender_title or '卫生站' in tender_title:
                    institute_type = '门诊/诊所'
                elif '临床检验中心' in tender_title:
                    institute_type = '临床检验中心'
                elif '急救中心' in tender_title or '急救站'in tender_title or \
                     '护理院' in tender_title or '护理站' in tender_title or \
                     '血站' in tender_title or '疾控中心' in tender_title:
                    institute_type = '其他诊疗机构'
                elif '公司' in tender_title:
                    institute_type = '企业'
                elif '大学' in tender_title:
                    institute_type = '大学'
                # print(tender_title)
                tender_publ = tender_node.select('i[class="fr font-12 color-999 mg-t5 mg-r5"]')
                tender_date = tender_publ[0].get_text()[5:]
                # print(tender_date)
            # --------------------------
            content_info = tender_node.select('span[class="item-value"]')
            content_method = content_info[0].get_text()
            # print(content_method)
            content_product = content_info[1].get_text()
            # print(content_product)
            content_deadline = content_info[2].get_text()
            # print(content_deadline)
            content_area = content_info[3].get_text()
            province = ''
            city = ''
            county = ''
            if content_area.endswith('省') or content_area.endswith('自治区'):
                province = content_area
            elif content_area.endswith('市'):
                city = content_area
            else:
                county = content_area
            # print(content_area)
            time.sleep(2)
            # -------------------------
            try:
                browser.find_element_by_link_text(tender_title).click()
                print('bid page success!')
            except:
                print('bid page fail!')
                break
            time.sleep(2)
            all_handles = browser.window_handles
            for handle in all_handles:
                if handle != search_window:
                    browser.switch_to.window(handle)
            time.sleep(2)
            # -------------------------
            bid_html = browser.page_source
            bid_soup = BeautifulSoup(bid_html, "html5lib")
            time.sleep(2)
            # -------------------------
            bid_list = bid_soup.select('div[class="position-relative"]')
            bid_list_size = len(bid_list)
            # print(bid_list_size)  # 1
            bid_node = bid_list[1]
            bid_info = bid_node.select('span')
            bid_info_size = len(bid_info)
            # print(bid_info_size)
            project_number = bid_info[1].get_text().strip().strip(';')
            announcement_type = bid_info[3].get_text().strip().strip(';')
            tender_method = bid_info[5].get_text().strip().strip(';')
            deadline = bid_info[7].get_text().strip().strip(';')
            tendering_agent = bid_info[9].get_text().strip().strip(';')
            bidding_area = bid_info[11].get_text().strip().strip(';')
            bidding_product = bid_info[13].get_text().strip().strip(';')
            industry = bid_info[15].get_text().strip().strip(';')

            tenderer_ptn1 = r'采购单位：(.*?)</p>'
            tenderer1 = re.findall(tenderer_ptn1, bid_html)
            tenderer_ptn2 = r'采购单位:(.*?)</p>'
            tenderer2 = re.findall(tenderer_ptn2, bid_html)

            tenderer_ptn3 = r'采购人：(.*?)</p>'
            tenderer3 = re.findall(tenderer_ptn3, bid_html)
            tenderer_ptn4 = r'采购人:(.*?)</p>'
            tenderer4 = re.findall(tenderer_ptn4, bid_html)

            tenderer_ptn5 = r'采购人名称：(.*?)</p>'
            tenderer5 = re.findall(tenderer_ptn5, bid_html)
            tenderer_ptn6 = r'采购人名称:(.*?)</p>'
            tenderer6 = re.findall(tenderer_ptn6, bid_html)

            tenderer_ptn7 = r'招标人：(.*?)</p>'
            tenderer7 = re.findall(tenderer_ptn7, bid_html)
            tenderer_ptn8 = r'招标人:(.*?)</p>'
            tenderer8 = re.findall(tenderer_ptn8, bid_html)

            tenderer_ptn9 = r'申请单位：(.*?)</p>'
            tenderer9 = re.findall(tenderer_ptn9, bid_html)
            tenderer_ptn10 = r'申请单位:(.*?)</p>'
            tenderer10 = re.findall(tenderer_ptn10, bid_html)

            tenderer = ''
            if len(tenderer1) > 0:
                tenderer = tenderer1[0]
            elif len(tenderer2) > 0:
                tenderer = tenderer2[0]
            elif len(tenderer3) > 0:
                tenderer = tenderer3[0]
            elif len(tenderer4) > 0:
                tenderer = tenderer4[0]
            elif len(tenderer5) > 0:
                tenderer = tenderer5[0]
            elif len(tenderer6) > 0:
                tenderer = tenderer6[0]
            elif len(tenderer7) > 0:
                tenderer = tenderer7[0]
            elif len(tenderer8) > 0:
                tenderer = tenderer8[0]
            elif len(tenderer9) > 0:
                tenderer = tenderer9[0]
            elif len(tenderer10) > 0:
                tenderer = tenderer10[0]
            if len(tenderer) > 0:
                institute_type = '政府机构'
                if '医院' in tenderer or '妇幼保健院' in tenderer or \
                   '防治院' in tenderer or '防治所' in tenderer or '防治站' in tenderer:
                    institute_type = '医院'
                elif '卫生服务中心' in tenderer or '卫生服务站' in tenderer or \
                     '卫生院' in tenderer or '疗养院' in tenderer:
                    institute_type = '基层医疗单位'
                elif '门诊部' in tenderer or '诊所' in tenderer or \
                     '卫生所' in tenderer or '医务室' in tenderer or \
                     '保健所' in tenderer or '卫生站' in tenderer:
                    institute_type = '门诊/诊所'
                elif '临床检验中心' in tenderer:
                    institute_type = '临床检验中心'
                elif '急救中心' in tenderer or '急救站' in tenderer or \
                     '护理院' in tenderer or '护理站' in tenderer or \
                     '血站' in tenderer or '疾控中心' in tenderer:
                    institute_type = '其他诊疗机构'
                elif '公司' in tenderer:
                    institute_type = '企业'
                elif '大学' in tenderer:
                    institute_type = '大学'

            browser.close()
            browser.switch_to.window(search_window)
            time.sleep(2)
            print('-------------------')
            sheet.append([today, data_type, first_published, project_number,
                          platform, content_product, tenderer, institute_type, tender_date, content_deadline,
                          tendering_agent, province, city, county, announcement_type, tender_type, tender_link])
        # --------------------------
        try:
            browser.find_element_by_link_text("下一页").click()
            print('next page success!')
        except:
            print('next page fail!')
            break
        time.sleep(2)
    # --------------------------
work_book.save(foreshow_file)

